<?php
/**
 * UEditor 上传处理
 *
 * Author: Zeon
 * Date: 2018/1/27
 * Created by Panxsoft.
 */
namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\UEditor\UEditorActionRequest;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use App\Services\Utils\Bosable;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;

class UEditorController extends Controller
{
    const IMAGE_FILED = "upfile";
    const ACTION_UPLOAD_IMG = "uploadimage";
    const ACTION_CONF = "config";
    const BOS_KEY_PREFIX = 'rich-text-images/';
    const STATE_SUCCESS = "SUCCESS";

    use ApiChecker,
        ApiResponser,
        Bosable;

    /**
     * UEditor 统一处理接口
     *
     * @param UEditorActionRequest $request
     * @return array
     * @throws \App\Exceptions\AdminManageException
     */
    public function index(UEditorActionRequest $request)
    {
        switch ($request->action) {
            case self::ACTION_CONF :
                return $this->config();

            case self::ACTION_UPLOAD_IMG :
                return $this->storeImage($request);

            default :
                $this->checkCanOperate(false, "无效的action参数");
        }
    }

    /**
     * @return array
     */
    public function config()
    {
        return [
            "imageUrl"        => route("ueditor") . "?action=" . self::ACTION_UPLOAD_IMG,
            "imageActionName" => self::ACTION_UPLOAD_IMG,
            "imagePath"       => "",
            "imageUrlPrefix"  => "",
            "imageFieldName"  => self::IMAGE_FILED,
            "imageMaxSize"    => 2048000, // byte
            "imageAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
        ];
    }

    /**
     * UEditor 上传 Bos 图片
     *
     * @param Request $request
     * @return array
     */
    public function storeImage(Request $request)
    {
        $image = $request->file(self::IMAGE_FILED);

        $url = $this->uploadFileToUrl($image);

        $res = [
            "original" => $image->getClientOriginalName(),
            "title"    => $image->getFilename(),
            "url"      => $url,
            "state"    => self::STATE_SUCCESS,
        ];

        return $res;
    }

    /**
     * @param UploadedFile $file
     * @return mixed
     */
    private function uploadFileToUrl(UploadedFile $file)
    {
        $bos_key = $this->uploadPostFile($file, self::BOS_KEY_PREFIX);

        $url = $this->getStaticUrl($bos_key);

        return $url;
    }


}
